package com.xsq.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.xsq.Constants;
import com.xsq.R;
import com.xsq.data.Records;
import com.xsq.utils.HttpUtil;
import com.xsq.utils.SharedPreferencesUtils;
import com.xsq.utils.StatusUtils;
import com.xsq.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class RecordsDialog extends Dialog {

	private Context context;
	private String title;
	private TextView merchName, merchWind, totalOrderAmount, totalActualAmount, totalDiscountAmount;
	private LayoutInflater inflater;
	private SmartRefreshLayout refresh_root;
	private RecyclerView mListView;
	private List<Records> mData;
	private RecordsAdapter mAdapter;
	private SharedPreferencesUtils spUtils;

	public RecordsDialog(Context context) {
		super(context, R.style.MyDialogStyleBottom);
	}

	public RecordsDialog(Context context, String title) {
		this(context);
		this.context = context;
		this.title = title;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_records_dialog);
		spUtils = new SharedPreferencesUtils(context, "DLX");
		inflater = LayoutInflater.from(context);
		TextView titleTextView = findViewById(R.id.title);
		Button okButton = findViewById(R.id.ok);
		titleTextView.setText(title);
		okButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
		setCanceledOnTouchOutside(false);

		merchName = findViewById(R.id.merchant_name);
		merchWind = findViewById(R.id.merchant_wind);
		totalOrderAmount = findViewById(R.id.totalOrderAmount);
		totalActualAmount = findViewById(R.id.totalActualAmount);
		totalDiscountAmount = findViewById(R.id.totalDiscountAmount);

		mData = new ArrayList<>();
		mAdapter = new RecordsAdapter();
		refresh_root = findViewById(R.id.refresh_root);
		mListView = findViewById(R.id.list);
		LinearLayoutManager layoutManager = new LinearLayoutManager(context);
		mListView.setLayoutManager(layoutManager);
		mListView.setAdapter(mAdapter);
		refresh_root.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
			@Override
			public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
			}

			@Override
			public void onRefresh(@NonNull RefreshLayout refreshLayout) {
				fetchCardRecords();
			}
		});
		refresh_root.autoRefresh();
		refresh_root.setEnableLoadMore(false);
	}

	@Override
	public void show() {
		try {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
					WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
			super.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected String getBaseUrl() {
		String baseUrl = spUtils.getObject("BASE_URL", String.class);
		return baseUrl;
	}

	private void fetchCardRecords() {
		HashMap<String, String> params = new HashMap<>();
		params.put("posSn", Utils.getAndroidId(context));
		params.put("startTime", Utils.getDateStr(new Date(), "yyyy-MM-dd"));
		params.put("endTime", Utils.getDateStr(new Date(), "yyyy-MM-dd"));
		HttpUtil.getInstance().post(getBaseUrl() + Constants.url_queryConsumeRecords, params, new Callback.CommonCallback<JSONObject>() {
			@Override
			public void onSuccess(JSONObject response) {
				LogUtil.e("response==" + response.toString());
				int code = response.optInt("code");
				if(code == 0) {
					mData.clear();
					Gson gson = new Gson();
					List<Records> records = gson.fromJson(response.optString("records"), new TypeToken<List<Records>>(){}.getType());
					if(records != null && records.size() > 0) {
						merchName.setText(records.get(0).getMerchantName());
						merchWind.setText(records.get(0).getWindowName());
                        String orderAmountStr = response.optJSONObject("statistic").optString("orderAmount");
                        String actualAmountStr = response.optJSONObject("statistic").optString("actualAmount");
                        String discountAmountStr = response.optJSONObject("statistic").optString("discountAmount");
                        totalOrderAmount.setText(new BigDecimal(orderAmountStr).divide(new BigDecimal(100)) + "元");
						totalActualAmount.setText(new BigDecimal(actualAmountStr).divide(new BigDecimal(100)) + "元");
						totalDiscountAmount.setText(new BigDecimal(discountAmountStr).divide(new BigDecimal(100)) + "元");
						mData.addAll(records);
						mAdapter.notifyDataSetChanged();
					}
					refresh_root.finishRefresh();
				}else {
					Toast.makeText(context, response.optString("msg"), Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				StatusUtils.handleError(ex, context);
			}

			@Override
			public void onCancelled(CancelledException cex) {
			}

			@Override
			public void onFinished() {
				/*String ddddd = "{\n" +
						"    \"msg\": \"操作成功\",\n" +
						"    \"statistic\": {\n" +
						"        \"tradeDate\": \"2019-09-23\",\n" +
						"        \"orderAmount\": 18800,\n" +
						"        \"actualAmount\": 16500,\n" +
						"        \"discountAmount\": 2300,\n" +
						"        \"posSn\": null,\n" +
						"        \"windowNo\": null,\n" +
						"        \"windowName\": null,\n" +
						"        \"merchantNo\": null,\n" +
						"        \"merchantName\": null,\n" +
						"        \"orgCode\": null\n" +
						"    },\n" +
						"    \"code\": 0,\n" +
						"    \"records\": [\n" +
						"        {\n" +
						"            \"recordId\": \"99fcfbaec5354935a73234cca1edf720\",\n" +
						"            \"tradeDate\": \"2019-09-23\",\n" +
						"            \"accountId\": \"3b3acee7b02b4d94b10800f003d53dda\",\n" +
						"            \"userCode\": \"123\",\n" +
						"            \"userType\": \"0\",\n" +
						"            \"userName\": \"张三\",\n" +
						"            \"cardNo\": \"eae44173\",\n" +
						"            \"cardSerialNo\": null,\n" +
						"            \"orderAmount\": 10000,\n" +
						"            \"actualAmount\": 8000,\n" +
						"            \"discountAmount\": 2000,\n" +
						"            \"posSn\": \"85c8da81b96a631c\",\n" +
						"            \"windowNo\": 2,\n" +
						"            \"windowName\": \"2号窗口\",\n" +
						"            \"merchantNo\": 1,\n" +
						"            \"merchantName\": \"肯德基\",\n" +
						"            \"orgCode\": \"PLA-NJACC\",\n" +
						"            \"createGmt\": \"2019-09-23 22:34:51\",\n" +
						"            \"updateGmt\": null\n" +
						"        },\n" +
						"        {\n" +
						"            \"recordId\": \"4b1c6ac120974e24adfee2bcb17d5687\",\n" +
						"            \"tradeDate\": \"2019-09-23\",\n" +
						"            \"accountId\": \"3b3acee7b02b4d94b10800f003d53dda\",\n" +
						"            \"userCode\": \"123\",\n" +
						"            \"userType\": \"0\",\n" +
						"            \"userName\": \"张三\",\n" +
						"            \"cardNo\": \"eae44173\",\n" +
						"            \"cardSerialNo\": null,\n" +
						"            \"orderAmount\": 8800,\n" +
						"            \"actualAmount\": 8500,\n" +
						"            \"discountAmount\": 300,\n" +
						"            \"posSn\": \"85c8da81b96a631c\",\n" +
						"            \"windowNo\": 2,\n" +
						"            \"windowName\": \"2号窗口\",\n" +
						"            \"merchantNo\": 1,\n" +
						"            \"merchantName\": \"肯德基\",\n" +
						"            \"orgCode\": \"PLA-NJACC\",\n" +
						"            \"createGmt\": null,\n" +
						"            \"updateGmt\": null\n" +
						"        }\n" +
						"    ]\n" +
						"}";
				try {
					JSONObject response = new JSONObject(ddddd);
					int code = response.optInt("code");
					if(code == 0) {
						mData.clear();
						Gson gson = new Gson();
						List<Records> records = gson.fromJson(response.optString("records"), new TypeToken<List<Records>>(){}.getType());
						if(records != null && records.size() > 0) {
							merchName.setText(records.get(0).getMerchantName());
							merchWind.setText(records.get(0).getWindowName());
							totalOrderAmount.setText(response.optJSONObject("statistic").optString("orderAmount"));
							totalActualAmount.setText(response.optJSONObject("statistic").optString("actualAmount"));
							totalDiscountAmount.setText(response.optJSONObject("statistic").optString("discountAmount"));
							mData.addAll(records);
							mAdapter.notifyDataSetChanged();
						}
						refresh_root.finishRefresh();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}*/
                refresh_root.finishRefresh();
			}
		});
	}

	private class RecordsAdapter extends RecyclerView.Adapter {

		@NonNull
		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
			RecordsViewHolder viewHolder = new RecordsViewHolder(inflater.inflate(R.layout.adapter_records, viewGroup, false));
			return viewHolder;
		}

		@Override
		public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
			final Records item = mData.get(i);
			RecordsViewHolder holder = (RecordsViewHolder)viewHolder;
			holder.recordIdText.setText(item.getRecordId());
			holder.createGmtText.setText(item.getCreateGmt());
			holder.userCodeText.setText(item.getUserCode());
			holder.userNameText.setText(item.getUserName());

            holder.orderAmountText.setText(new BigDecimal(item.getOrderAmount()).divide(new BigDecimal(100)) + "元");
            holder.actualAmountText.setText(new BigDecimal(item.getActualAmount()).divide(new BigDecimal(100)) + "元");
            holder.discountAmountText.setText(new BigDecimal(item.getDiscountAmount()).divide(new BigDecimal(100)) + "元");
		}

		@Override
		public int getItemCount() {
			return mData == null ? 0 : mData.size();
		}

		class RecordsViewHolder extends RecyclerView.ViewHolder {

			private TextView recordIdText;
			private TextView createGmtText;
			private TextView userCodeText;
			private TextView userNameText;
			private TextView orderAmountText;
			private TextView actualAmountText;
			private TextView discountAmountText;
			public RecordsViewHolder(@NonNull View itemView) {
				super(itemView);
				recordIdText = itemView.findViewById(R.id.recordId);
				createGmtText = itemView.findViewById(R.id.createGmt);
				userCodeText = itemView.findViewById(R.id.userCode);
				userNameText = itemView.findViewById(R.id.userName);
				orderAmountText = itemView.findViewById(R.id.orderAmount);
				actualAmountText = itemView.findViewById(R.id.actualAmount);
				discountAmountText = itemView.findViewById(R.id.discountAmount);
			}
		}
	}
}
